$(document).ready(function () {

    var newMessageSelector = "#newMessage";
    var getMessagesFlag = false;

    InitialLoad();
    function InitialLoad() {
        $.ajax({
            url: "http://localhost:5381/ChatService.svc/Channels/all",
            type: "GET",
            dataType: 'json',
            async: false,
            success: function (data) {
                $("#channels").html('');
                if (data != null) {
                    $.each(data, function (key, channel) {
                        var content = '<div class="channel">#' + channel.ChannelName + '</div>';
                        $("#channelsBody").prepend(content);
                    });
                }
                else {
                    alert("error");
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                //                        alert(xhr.status);
                //                        alert(thrownError);
            }
        });

        $(".channel").bind('click', BindChannelClick);
        $("#channelsBody div:first").click();
    }

    $("#post").click(function () {
        PostNewMessage(this);
    });

    function BindChannelClick() {
        $("#channelsBody div").removeClass("selected");
        $(this).addClass("selected");

        FillChatWithMessages(this);
    }

    function FillChatWithMessages(obj) {
        var text = $(obj).text();
        var channelName = GetSelectedChannel();
        var urlPath = document.location.protocol + "//" + document.location.host + "/ChatService.svc/GetMessagesInChannel/" + channelName;
        getMessagesFlag = true;

        $.ajax({
            url: urlPath,
            type: "GET",
            dataType: 'json',
            async: true,
            success: function (data) {
                $("#channels").html('');
                if (data != null) {
                    var content = "";
                    $.each(data, function (key, message) {
                        content += '<div class="message">' + message.Body + '</div>';

                    });

                    $("#chatBody").html('');
                    $("#chatBody").prepend(content);
                    MoveScrollToBottom();
                    getMessagesFlag = false;
                }
                else {
                    //alert("error");
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                //                        alert(xhr.status);
                //                        alert(thrownError);
            }
        });
    }

    function GetNewMessages() {
        if (getMessagesFlag == false) {
            $(".channel.selected").click();
            MoveScrollToBottom();
        }
    }

    function MoveScrollToBottom() {
        var objDiv = document.getElementById("chatBody");
        objDiv.scrollTop = objDiv.scrollHeight;
    }

    function PostNewMessage() {
        var messageBody = $("#newMessage").val();
        $(newMessageSelector).val('');

        var post = new Object();
        post.Body = messageBody;
        post.ChannelName = GetSelectedChannel();
        post.Date = new Date();

        var dataToSend = '{"post":' + JSON.stringify(post) + '}';
        var urlPath = document.location.protocol + "//" + document.location.host + "/ChatService.svc/PostMessage";

        $.ajax({
            url: urlPath,
            type: "Post",
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            async: false,
            data: dataToSend,
            success: function (response) {

            },
            error: function (xhr, ajaxOptions, thrownError) {
                //                        alert(xhr.status);
                //                        alert(thrownError);
            }
        });
    }

    function GetSelectedChannel() {
        var text = $(".channel.selected").text();
        var txt = text.substring(1);
        return txt;
    }

    var time = setInterval(GetNewMessages, 1000);
});